﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Xna.Framework.Storage;

namespace MDXModelImporter
{   

    class MDXParse
    {        
	    public int	            mSize;
        public bool	            mLoaded;
	    public mdxCameras	    mCameras;
	    public mdxVersion	    mVersion;
        public mdxInfo          mInfo;
	    public mdxGeometry		mGeometry;
	    public mdxSequence		mSequences;
	    public mdxTextures		mTextures;
	    public mdxMaterialMap	mMaterials;
		
        public MDXParse()
        {
        }

        //.mdx file path
        public void LoadFromFile(string filename)
        {
            byte[] bytes = File.ReadAllBytes(filename);
            FileStream fs;
            try
            {
                fs = File.Open(filename, FileMode.Open);                
            }
            catch (Exception ex)
            {
                Log.Write("Error .mdx file not found !");
                throw ex;
            }
            mSize = (int)(fs.Length);
            if(mSize==0)
            {
                Log.Write("Error .mdx file size is 0");
                throw new Exception("Error .mdx file's size is 0");
            }
            BinaryReader br = new BinaryReader(fs);
            fs.Position = 0;
            //...............
            ParseStream(br);

            br.Close();
            fs.Close();
        }

        //load from memory bytes
        //byte[] bytes    = File.ReadAllBytes(filename);
        public void LoadFromMemory(byte[] bytes)
        {
            mSize = bytes.Length;
            if (mSize == 0)
            {
                Log.Write("Error .mdx file size is 0");
                throw new Exception("Error .mdx file's size is 0");
            }
            // read summary of data stored in the md2 file
            MemoryStream ms = new MemoryStream(bytes);
            BinaryReader br = new BinaryReader(ms);
            ms.Position = 0;
            //.........
            ParseStream(br);

            br.Close();
            ms.Close();
        }

		//e.g. in XLDM out MDLX			
        private UInt32 ReverseTag(string intag)
        {
            return 0;
        }

        protected void ParseStream(BinaryReader br)
        {
            UInt32 tag = br.ReadUInt32;//it should be 'MDLX' in reverse;How to check? I don't know yet
            if (tag != ReverseTag("MDLX"))
            {
                Log.Write("Error .mdx file size is 0");
                throw new Exception("Error .mdx file's size is 0");
            }


        }
	

        //void			Render				(void);
        //void			Load				(char* inName);
        //bool			LoadFromMemory(const char* inBuf, const long inBufSize);
    }
}
